﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SPCFMedicineInformer.DocumentTypes;
using Vega.USiteBuilder;
using SPCFMedicineInformer.Members;
using System.Web.Security;

using umbraco.MacroEngines;
using umbraco.NodeFactory;
using umbraco;
using Fonqi.Umbraco;
using SPCFMedicineInformer.Constants;

namespace SPCFMedicineInformer.Masterpages
{
    public partial class ContentMedicineCategory : System.Web.UI.MasterPage
    {
        public int NodeToDeleteId { get; set; }
        public int PageNum { get; set; }
        public int TotalRec { get; set; }
        int limitPerPage = 20;
        string chr = "";
        string query = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            chr = Request.QueryString["chr"] != null ? Request.QueryString["chr"].ToString().ToCharArray().FirstOrDefault().ToString().ToLower() : "";
            query = Request.QueryString["query"] != null ? Request.QueryString["query"].ToString() : "";
            bool isBranded = Request.QueryString["ib"] != null ? true : false;
            bool isGeneric = Request.QueryString["ig"] != null ? true : false;
            if (!IsPostBack)
            {
                txtSearchMedicine.Text = query;
                cbBranded.Checked = isBranded;
                cbGenericName.Checked = isGeneric;
                string strpage = Request.QueryString["p"] != null ? Request.QueryString["p"].ToString() : "1";
                int tempInt;
                PageNum = int.TryParse(strpage, out tempInt) ? tempInt : 1;
                BindGrid();
                
            }

        }
        
        void BindGrid()
        {
            bool isLetter = Char.IsLetter(chr.FirstOrDefault()) || chr == "";
            var list = new Node(-1).GetDescendantNodes().Where(node => (node.NodeTypeAlias == "MedicineItem" && cbBranded.Checked) || 
                                                            (node.NodeTypeAlias == "MedicineGenericName" && cbGenericName.Checked))
                                                        .Where(a => (!string.IsNullOrEmpty(a.GetPropertyAsString(UmbracoPropertyName.MEDICINE_NAME_MT)) && a.NodeTypeAlias == "MedicineItem" ? a.GetPropertyAsString(UmbracoPropertyName.MEDICINE_NAME_MT) : !string.IsNullOrEmpty(a.GetPropertyAsString(UmbracoPropertyName.GENERIC_NAME_MT)) && a.NodeTypeAlias == "MedicineGenericName" ? a.GetPropertyAsString(UmbracoPropertyName.GENERIC_NAME_MT) : a.Name).ToLower().ContainsAny(query.ToLower()) &&
                                                            (
                                                                (a.Name.ToLower().StartsWith(chr) && isLetter) ||
                                                                (!Char.IsLetter(a.Name.FirstOrDefault()) && !isLetter)
                                                            )
                                                            )
                                                        .OrderBy(a => a.Name)
                                                        .ToList();
            TotalRec = list.Count();
            list = list.Skip((PageNum - 1) * limitPerPage).Take(limitPerPage).ToList();
            DisplayPaging();
            RepMedicineItem.DataSource = list;
            RepMedicineItem.DataBind();
        }
        void DisplayPaging()
        {
            int maxPage = (TotalRec / limitPerPage) + (TotalRec % limitPerPage > 0 ? 1 : 0);
            List<string> pageList = new List<string>();
            for (int i = 1; i <= maxPage; i++)
            {
                pageList.Add(i.ToString());
            }

            rptPaging.DataSource = pageList;
            rptPaging.DataBind();

        }

        protected void repeater_ItemCommand(object source, RepeaterCommandEventArgs e)
        {
            int intTemp = 0;
            if (int.TryParse((string)e.CommandArgument, out intTemp))
            {
                switch (e.CommandName.ToLower())
                {
                    case "paging":
                        PageNum = intTemp;
                        BindGrid();
                        break;
                }
            }
        }     
        protected void btnFilter_Click(object sender, EventArgs e)
        {
            PageNum = 1;
            string checkType = cbBranded.Checked ? "&ib=1" : "";
            checkType += cbGenericName.Checked ? "&ig=1" : "";
            Response.Redirect("/medicines?query=" + txtSearchMedicine.Text + checkType);
        }
        protected void Repeater_ItemDatabound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                LinkButton lb = (LinkButton)e.Item.FindControl("linkButPaging");
                Literal lit = (Literal)e.Item.FindControl("litPaging");
                if (PageNum.ToString() == lit.Text)
                {
                    lb.CssClass = "current";
                }
            }

        }
        protected void rptSearchResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Node node = (Node)e.Item.DataItem;
                if (!string.IsNullOrEmpty(node.Name))
                {
                    Literal litLink = (Literal)e.Item.FindControl("litLink");
                    Literal litType = (Literal)e.Item.FindControl("litType");
                    Literal litCateogry = (Literal)e.Item.FindControl("litCategory");
                    switch (node.NodeTypeAlias)
                    {
                        case "MedicineGenericName":
                            litType.Text = "Generic Medicine";
                            litLink.Text = string.Concat(node.Parent.Id.ToString(), "/", node.Id.ToString());
                            litCateogry.Text = node.Parent.Name;
                        break;
                        case "MedicineItem":
                            litType.Text = "Branded Medicine";
                            litLink.Text = string.Concat(node.Parent.Parent.Id.ToString(), "/", node.Parent.Id.ToString(), "/", node.Id.ToString());
                            litCateogry.Text = node.Parent.Parent.Name;
                        break;
                    }

                }
            }
        }
    }
}